<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-06-09 16:25:04
 * @LastEditors: william
 * @LastEditTime: 2025-10-16 15:57:00
-->
<template>
  <nw-PageTitle title="调料管理" isBack />
  <nw-PageContainer>
    <nw-LoadingPage :loading="loading"></nw-LoadingPage>
    <up-toast ref="uToastRef" />
    <scroll-view class="scroll-content" scroll-y>
      <view class="lists">
        <view class="list list-2">
          <view class="list-head">
            <view class="lh-left">选择炒菜机</view>
          </view>
          <view class="ul">
            <view
              :class="[
                'li',
                {
                  active: deviceSn === row.sn
                }
              ]"
              v-for="(row, i) in bindDeviceList"
              :key="row"
              @click="handleDeviceClick(row)"
            >
              <image
                :src="
                  deviceSn === row.sn
                    ? getViteImageUrl('recipe/cookingMachineSelected.png')
                    : getViteImageUrl('recipe/cookingMachine.png')
                "
                mode="aspectFit"
                class="device-img"
              />
              <view class="li-text">{{ row.name }}</view>
            </view>
          </view>
        </view>
        <view class="list">
          <view class="list-head">
            <view class="lh-left">粉料状态</view>
          </view>
          <view class="ul">
            <view
              class="li2 yellow"
              :class="{
                grey: !row.ingredientRemain,
                red: !row.status,
                active: ingredientRow.ingredientCode === row.ingredientCode
              }"
              v-for="(row, i) in powderBoxList"
              :key="row"
              @click="handleRowClick(row)"
              @longpress="handleLiLongpress(row)"
            >
              <view class="li-row">
                <view class="li-title">{{ row.name }}</view>
                <view class="li-content">
                  <view class="lc-label">{{ row.ingredientName }}</view>
                  <view class="lc-value">{{ row.ingredientRemain }}g</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="list">
          <view class="list-head">
            <view class="lh-left">液料状态</view>
          </view>
          <view class="ul">
            <view
              class="li2 green"
              :class="{
                grey: !row.ingredientRemain,
                red: !row.status,
                active: ingredientRow.ingredientCode === row.ingredientCode
              }"
              v-for="(row, i) in materialBoxList"
              :key="row"
              @click="handleRowClick(row)"
              @longpress="handleLiLongpress(row)"
            >
              <view class="li-title">{{ row.name }}</view>
              <view class="li-content">
                <view class="lc-label">{{ row.ingredientName }}</view>
                <view class="lc-value">{{ row.ingredientRemain }}ml</view>
              </view>
            </view>
          </view>
        </view>
        <view class="list">
          <view class="list-head">
            <view class="lh-left">酱料状态</view>
          </view>
          <view class="ul">
            <view
              class="li2 green"
              :class="{
                grey: !row.ingredientRemain,
                red: !row.status,
                active: ingredientRow.ingredientCode === row.ingredientCode
              }"
              v-for="(row, i) in sauceBoxList"
              :key="row"
              @click="handleRowClick(row)"
              @longpress="handleLiLongpress(row)"
            >
              <view class="li-title">{{ row.name }}</view>
              <view class="li-content">
                <view class="lc-label">{{ row.ingredientName }}</view>
                <view class="lc-value">{{ row.ingredientRemain }}g</view>
              </view>
            </view>
            <view
              class="li2 pink"
              :class="{
                grey: !row.ingredientRemain,
                red: !row.status,
                active: ingredientRow.ingredientCode === row.ingredientCode
              }"
              v-for="(row, i) in gourdBoxList"
              :key="row"
              @click="handleRowClick(row)"
              @longpress="handleLiLongpress(row)"
            >
              <view v-if="!i" class="list-head list-head2">
                <view class="lh-left">勾芡状态</view>
              </view>
              <view class="li-title">{{ row.name }}</view>
              <view class="li-content">
                <view class="lc-label">{{ row.ingredientName }}</view>
                <view class="lc-value">{{ row.ingredientRemain }}ml</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="lists">
        <view class="list">
          <view class="list-head">
            <view class="lh-left">调料校准</view>
            <view class="lh-right" @click="handleViewMethod">
              <view class="text">点击查看方法</view>
              <ForwardIcons />
            </view>
          </view>
          <view class="items">
            <view class="i-top">
              <view class="nw-label">待校准的调料：</view>
              <view class="nw-value">{{ ingredientRow.ingredientName }}</view>
            </view>
            <view class="i-content">
              <up-row class="nw-row">
                <up-col span="6">
                  <view class="i-item">
                    <view class="nw-label">投放次数1:</view>
                    <nw-Input
                      v-model.number="formData.putNumber1"
                      type="number"
                      placeholder="输入"
                      verifyType="nzint"
                      :maxlength="2"
                      :clearable="false"
                      class="nw-input"
                    >
                      <template #right>
                        <view class="unit">g(ml)</view>
                      </template>
                    </nw-Input>
                    <nw-Button
                      :class="{
                        'nw-available-btn': formData.putNumber1
                      }"
                      text="投放"
                      @click="handleLaunch(1)"
                    ></nw-Button>
                  </view>
                </up-col>
                <up-col span="6">
                  <view class="i-item">
                    <view class="nw-label">投放次数2:</view>
                    <nw-Input
                      v-model.number="formData.putNumber2"
                      type="number"
                      placeholder="输入"
                      verifyType="nzint"
                      :maxlength="2"
                      :clearable="false"
                      class="nw-input"
                    >
                      <template #right>
                        <view class="unit">g(ml)</view>
                      </template>
                    </nw-Input>
                    <nw-Button
                      :class="{
                        'nw-available-btn': formData.putNumber2
                      }"
                      text="投放"
                      @click="handleLaunch(2)"
                    ></nw-Button>
                  </view>
                </up-col>
                <up-col span="6">
                  <view class="i-item" style="margin-top: 20rpx">
                    <view class="nw-label">投放次数3:</view>
                    <nw-Input
                      v-model.number="formData.putNumber3"
                      type="number"
                      placeholder="输入"
                      verifyType="nzint"
                      :maxlength="2"
                      :clearable="false"
                      class="nw-input"
                    >
                      <template #right>
                        <view class="unit">g(ml)</view>
                      </template>
                    </nw-Input>
                    <nw-Button
                      :class="{
                        'nw-available-btn': formData.putNumber3
                      }"
                      text="投放"
                      @click="handleLaunch(3)"
                    ></nw-Button>
                  </view>
                </up-col>
              </up-row>
            </view>
          </view>
          <view class="items">
            <view class="i-content">
              <up-row class="nw-row">
                <up-col span="6">
                  <view class="i-item">
                    <view class="nw-label">实际出料：</view>
                    <nw-Input
                      v-model.number="formData.putNumber"
                      type="number"
                      verifyType="nzint"
                      :maxlength="2"
                      :clearable="false"
                      class="nw-input"
                    >
                      <template #right>
                        <view class="unit">g(ml)</view>
                      </template>
                    </nw-Input>
                    <nw-Button
                      :class="{
                        'nw-available-btn':
                          formData.putNumber1Status &&
                          formData.putNumber2Status &&
                          formData.putNumber3Status &&
                          formData.putNumber
                      }"
                      text="自动校准"
                      @click="handleCalib"
                    ></nw-Button>
                  </view>
                </up-col>
              </up-row>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <FeedCalibr
      v-if="feedCalibrVisible"
      v-model="feedCalibrVisible"
      @update="getDataList"
    />
    <IngredientBox
      v-if="ingredientBoxVisible"
      v-model="ingredientBoxVisible"
      :seasonCodeList="seasonCodeList"
      :deviceSn="deviceSn"
      :row="ingredientBoxRow"
      @update="ingredientBoxUpdate"
    />
    <SeasonCalibBox
      v-if="seasonCalibBoxVisible"
      v-model="seasonCalibBoxVisible"
    />
    <CalibMethod v-if="calibMethodVisible" v-model="calibMethodVisible" />
    <RemainAlarm
      v-if="remainAlarmVisible"
      v-model="remainAlarmVisible"
      :names="remainAlarmNames"
    />
  </nw-PageContainer>
</template>

<script setup>
import FeedCalibr from './component/FeedCalibr.vue'
import IngredientBox from './component/IngredientBox.vue'
import SeasonCalibBox from './component/SeasonCalibBox.vue'
import CalibMethod from './component/CalibMethod.vue'
import RemainAlarm from './component/RemainAlarm.vue'

import { deviceProtocolManualService } from '@/service/deviceProtocolManualService.js'
import { deviceProtocolSettingService } from '@/service/deviceProtocolSettingService.js'

const { updateDevicePeripheralRatio } = useDeviceStore()
const { bindDeviceList } = storeToRefs(useDeviceStore())
const {getAnGoalByDeviceAndIngredient} = useCookingStore()
const loading = ref(false)
const uToastRef = ref(null)
const deviceSn = ref('')
const ingredientRow = ref({})
const formData = ref({
  putNumber1: '',
  putNumber1Status: false,
  putNumber2: '',
  putNumber2Status: false,
  putNumber3: '',
  putNumber3Status: false,
  putNumber: ''
})
// 类别参数
const powderBoxList = ref([])
const materialBoxList = ref([])
const sauceBoxList = ref([])
const gourdBoxList = ref([])
const seasonCodeList = ref([])
// 弹框参数
const feedCalibrVisible = ref(false)
const ingredientBoxVisible = ref(false)
const ingredientBoxRow = ref({})
const seasonCalibBoxVisible = ref(false)
const calibMethodVisible = ref(false)
const remainAlarmVisible = ref(false)
const remainAlarmNames = ref([])

watch(
  [() => bindDeviceList.value, () => deviceSn.value],
  (nv, ov) => {
    console.log('nv', nv)
    // 动态匹配每个设备的盒类数据
    const deviceObj = nv[0].find(item => item.sn === nv[1]) || {}
    const list = deviceObj.peripheralList || []
    powderBoxList.value = list.filter(item => item.type === 2) || []
    materialBoxList.value = list.filter(item => item.type === 3) || []
    sauceBoxList.value = list.filter(item => item.type === 4) || []
    gourdBoxList.value = list.filter(item => item.type === 5) || []
    console.log('powderBoxList.value', powderBoxList.value)
  },
  {
    immediate: true,
    deep: true
  }
)

onMounted(_ => {
  //
})

const handleDeviceClick = row => {
  console.log('handleDeviceClick', row)
  deviceSn.value = row.sn
  nextTick(() => {
    // 动态计算调料的余量百分比
    remainAlarmNames.value = []
    ;[
      ...powderBoxList.value,
      ...materialBoxList.value,
      ...sauceBoxList.value,
      ...gourdBoxList.value
    ].forEach(item => {
      const limit = item.type === 2 || item.type === 4 ? 1000 : 2000
      if (item.ingredientRemain / limit < 0.05) {
        remainAlarmNames.value.push(item.ingredientName || item.name)
      }
    })
    if (remainAlarmNames.value.length) remainAlarmVisible.value = true
    console.log('remainAlarmNames.value', remainAlarmNames.value)
  })
}

const handleRowClick = row => {
  console.log('handleRowClick', row)
  // if (row.status && row.control) ingredientRow.value = row
  if (row.status && row.ingredientCode) ingredientRow.value = row
}

const handleLiLongpress = row => {
  console.log('handleLiLongpress', row)
  ingredientBoxVisible.value = true
  ingredientBoxRow.value = row
  formData.value.putNumber1Status = false
  formData.value.putNumber2Status = false
  formData.value.putNumber3Status = false
  seasonCodeList.value = [
    ...powderBoxList.value,
    ...materialBoxList.value,
    ...sauceBoxList.value,
    ...gourdBoxList.value
  ].reduce((prev, curr) => {
    if (row.ingredientCode !== curr.ingredientCode)
      prev.push(curr.ingredientCode)
    return prev
  }, [])
}

const handleViewMethod = row => {
  console.log('handleViewMethod', row)
  calibMethodVisible.value = true
}

const submitCheck = _ => {
  if (!deviceSn.value) {
    uToastRef.value.show({
      type: 'error',
      message: '请先选择设备',
      duration: 2 * 1000
    })
    return false
  }

  if (!ingredientRow.value.ingredientCode) {
    uToastRef.value.show({
      type: 'error',
      message: '请先选择调料盒',
      duration: 2 * 1000
    })
    return false
  }

  return true
}

const handleLaunch = type => {
  if (!submitCheck()) return

  const dataMap = {
    1: {
      value: formData.value.putNumber1,
      statusKey: 'putNumber1Status'
    },
    2: {
      value: formData.value.putNumber2,
      statusKey: 'putNumber2Status'
    },
    3: {
      value: formData.value.putNumber3,
      statusKey: 'putNumber3Status'
    }
  }
  console.log('handleLaunch', dataMap[type].value, ingredientRow.value)

  if (
    !dataMap[type].value ||
    dataMap[type].value < 2 ||
    dataMap[type].value > 20
  ) {
    uToastRef.value.show({
      type: 'error',
      message: '投放的重量限制在2~20g(ml)',
      duration: 2 * 1000
    })
    return
  }

  // 调料盒剩余数量小于投放数量
  if (dataMap[type].value > ingredientRow.value.ingredientRemain) {
    uToastRef.value.show({
      type: 'error',
      message: '调料盒剩余数量不足，请添加调料',
      duration: 2 * 1000
    })
    return false
  }

  const device = bindDeviceList.value.find(item => item.sn === deviceSn.value) || {}
  const targetGoal = getAnGoalByDeviceAndIngredient(ingredientRow.value.ingredientCode, device, dataMap[type].value * 1)
  
  deviceProtocolManualService
    .manualAddSeasoning(deviceSn.value, [
      {
        driverId: ingredientRow.value.driverId,
        goal: targetGoal
      }
    ])
    .then(r => {
      console.log('manualAddSeasoning-发送消息成功：', r)
      formData.value[dataMap[type].statusKey] = true
      uToastRef.value.show({
        message: '投放成功',
        duration: 500
      })
    })
    .catch(e => {
      console.log('manualAddSeasoning-发送消息失败：', e)
      uToastRef.value.show({
        message: '投放失败，请重新投放',
        duration: 500
      })
    })
}

const handleCalib = _ => {
  const {
    putNumber1,
    putNumber1Status,
    putNumber2,
    putNumber2Status,
    putNumber3,
    putNumber3Status,
    putNumber
  } = formData.value

  if (putNumber1Status && putNumber2Status && putNumber3Status) {
    const baseValue = (putNumber1 * 1 + putNumber2 * 1 + putNumber3 * 1) / 3
    const multiplier = ingredientRow.value.type === 3 ? 7 : 1 // 液料目标goal / 3 * 7 就是驱动对应的控制投放目标
    const ratio = ((baseValue * multiplier) / putNumber).toFixed(2) * 1

    seasonCalibBoxVisible.value = true
    deviceProtocolSettingService
      .calibrationSeasoningRatio(
        deviceSn.value,
        ingredientRow.value.driverId,
        ratio
      )
      .then(r => {
        console.log('calibrationSeasoningRatio-发送消息成功：', r)
        uToastRef.value.show({
          message: '自动校准成功',
          duration: 500
        })

        seasonCalibBoxVisible.value = false

        // 更新store中对应设备的调料盒比例
        updateDevicePeripheralRatio(
          deviceSn.value,
          ingredientRow.value.driverId,
          ratio
        )
      })
      .catch(e => {
        console.log('calibrationSeasoningRatio-发送消息失败：', e)
        uToastRef.value.show({
          message: '自动校准失败，请重新自动校准',
          duration: 500
        })
        seasonCalibBoxVisible.value = false
      })
  }
}

const ingredientBoxUpdate = _ => {
  console.log('ingredientBoxUpdate')
  // 清除投发记录
  if (String(ingredientRow.value.status) === '0') {
    ingredientRow.value = {}
    formData.value = {
      putNumber1: '',
      putNumber1Status: false,
      putNumber2: '',
      putNumber2Status: false,
      putNumber3: '',
      putNumber3Status: false,
      putNumber: ''
    }
  }
  uToastRef.value.show({
    type: 'success',
    message: '修改成功'
  })
}
</script>

<style lang="scss" scoped>
.scroll-content {
  height: calc(100%);
  overflow: hidden;
  box-sizing: border-box;
}

.lists {
  margin: 20rpx 20rpx 24rpx;
  padding: 0 22rpx 24rpx;
  border-radius: 18rpx;
  background-color: var(--bg-color);
  box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(6, 29, 23, 0.03);
  overflow: hidden;
  + .lists {
    margin-top: 0;
    padding-bottom: 0;
    .list {
      padding-bottom: 0;
    }
  }
  .list {
    padding: 20rpx 0 24rpx;
    + .list {
      border-top: 1rpx solid var(--border-color);
    }
    .list-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 4rpx;
      padding-bottom: 22rpx;
      .lh-left {
        flex-shrink: 0;
        font-size: 22rpx;
        font-weight: 600;
        color: var(--color-333);
      }
      .lh-right {
        display: flex;
        align-items: center;
        line-height: 24rpx;
        .text {
          line-height: 20rpx;
          font-size: 22rpx;
          font-weight: 400;
          color: var(--color-666);
        }
        .uni-icons {
          margin-top: 4rpx;
          margin-left: 10rpx;
        }
      }
    }
  }
  .list-2 {
    padding-top: 28rpx;
    .list-head {
      padding-bottom: 26rpx;
      .lh-left {
        font-size: 26rpx;
      }
    }
  }
}

.ul {
  display: flex;
  flex-wrap: wrap;
  padding: 0 9rpx;
  box-sizing: border-box;
  .li {
    width: 112rpx;
    height: 112rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 24rpx 4rpx 18rpx;
    background-color: var(--body-theme);
    border: 2rpx solid var(--body-theme);
    box-sizing: border-box;
    + .li {
      margin-left: 20rpx;
    }
    &:nth-child(5n + 1) {
      margin-left: 0;
    }
    &:nth-child(n + 6) {
      margin-top: 20rpx;
    }
    &.active {
      background-color: var(--active-bg-color);
      color: var(--main-theme);
      border-color: var(--main-theme);
      .li-text {
        color: var(--main-theme);
      }
    }
    .device-img {
      flex-shrink: 0;
      display: block;
      width: 38rpx;
      height: 38rpx;
    }
    .li-text {
      margin-top: 14rpx;
      line-height: 16rpx;
      font-size: 16rpx;
      font-weight: 400;
      color: var(--color-333);
    }
  }
  .li2 {
    position: relative;
    width: 98rpx;
    height: 118rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 14rpx 4rpx;
    background-color: var(--body-theme);
    border-radius: 12rpx;
    box-sizing: border-box;
    + .li2 {
      margin-left: 12rpx;
    }
    &:nth-child(6n + 1) {
      margin-left: 0;
    }
    &:nth-child(n + 7) {
      margin-top: 14rpx;
    }
    &.yellow {
      background-color: #fdf6da;
    }
    &.green {
      background-color: #dff3fc;
    }
    &.pink {
      background-color: #ffeede;
    }
    &.grey {
      background-color: #aaa;
    }
    &.red {
      background-color: var(--color-red);
    }
    &.red,
    &.grey {
      .li-title {
        color: var(--color-fff);
      }
      .li-content {
        .lc-label {
          color: var(--color-fff);
        }
        .lc-value {
          color: var(--color-fff);
        }
      }
    }
    &.active {
      background-color: var(--active-bg-color);
      color: var(--main-theme);
      border: 2rpx solid var(--main-theme);
      .li-title {
        color: var(--main-theme);
      }
      .li-content {
        .lc-label {
          color: var(--main-theme);
        }
        .lc-value {
          color: var(--main-theme);
        }
      }
    }
    .li-title {
      line-height: 16rpx;
      font-size: 18rpx;
      font-weight: 400;
      text-align: center;
      color: var(--color-999);
    }
    .li-content {
      text-align: center;
      .lc-label {
        margin-top: 20rpx;
        line-height: 20rpx;
        font-size: 22rpx;
        font-weight: 500;
        color: var(--color-333);
      }
      .lc-value {
        margin-top: 18rpx;
        line-height: 14rpx;
        font-size: 18rpx;
        font-weight: 400;
        color: var(--color-333);
      }
    }
    .list-head2 {
      position: absolute;
      left: 0;
      top: -54rpx;
      padding-left: 0;
    }
  }
}

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 24rpx 0 32rpx;
  border-top: 1rpx solid var(--border-color);

  .i-top {
    display: flex;
    align-items: center;
    padding-bottom: 30rpx;
    .nw-label {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      font-size: 22rpx;
      font-weight: 600;
      color: var(--color-666);
    }

    .nw-value {
      font-size: 22rpx;
      font-weight: 600;
      color: var(--color-333);
    }
  }

  .nw-row {
    display: flex;
    flex-wrap: wrap;
  }

  .i-item {
    display: flex;
    align-items: center;

    .nw-label {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      margin-right: 8rpx;
      font-size: 18rpx;
      font-weight: 400;
      color: var(--color-666);
    }
    .nw-input {
      flex: initial;
      min-width: 128rpx;
      width: 128rpx;
    }
    :deep(.uni-easyinput) {
      .uni-easyinput__placeholder-class {
        font-size: 18rpx !important;
      }
      .uni-input-input {
        font-size: 18rpx;
      }
    }
    :deep(.uni-easyinput__content-input) {
      padding: 0 !important;
      text-align: center;
    }
  }

  .nw-form-item {
    margin-bottom: 0;
  }

  .nw-input-wrap {
    display: flex;
    align-items: center;
  }
  .unit {
    margin: 0 10rpx 0 4rpx;
    font-size: 18rpx;
    font-weight: 400;
    color: var(--color-999);
  }
}

.nw-button-wrap {
  margin-left: 6rpx;
  :deep(.nw-button) {
    height: 40rpx;
    border-radius: 4rpx;
    background-color: #e7f9f3 !important;
    border-color: #e7f9f3 !important;
    .u-button__text {
      font-size: 18rpx !important;
      font-weight: 400;
      color: var(--main-theme) !important;
    }
    .u-button__loading-text {
      font-size: 18rpx !important;
      font-weight: 400;
      color: var(--main-theme) !important;
    }
    &:not(.u-button--disabled) .u-button__text {
      color: var(--main-theme) !important;
    }
  }
  :deep(.nw-button.nw-available-btn) {
    background-color: var(--main-theme) !important;
    border-color: var(--main-theme) !important;
    .u-button__text {
      color: var(--color-fff) !important;
    }
    .u-button__loading-text {
      color: var(--color-fff) !important;
    }
    &:not(.u-button--disabled) .u-button__text {
      color: var(--color-fff) !important;
    }
  }
}
</style>
